<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 用户操作类
 *
 * @author LeeNux
 * @version 1.0
 */
class User {
	protected $CI;
	public function __construct() {
		$this->CI = & get_instance ();
		$this->CI->load->model ( 'user_model' );
	}
	/**
	 * 验证用户密码
	 *
	 * @param array $whereArr        	
	 * @param string $password        	
	 */
	public function validPwd($whereArr, $password) {
		$re = $this->CI->user_model->row ( $whereArr );
		if (is_array ( $re ) && $password === $this->_decrypt ( $re['password'] )) {
			// return $this->_decrypt ( $re['password'] );
			return TRUE;
		} else {
			return FALSE;
		}
	}
	/**
	 * 添加用户
	 *
	 * @param string $email        	
	 * @param string $password        	
	 */
	public function addUser($email, $password) {
		$re = FALSE;
		$dataArr = array(
				'email' => $email, 
				'password' => $this->_encrypt ( $password ), 
				'createtime' => time () 
		);
		if (! $this->isExistUser ( $email )) {
			$re = $this->CI->user_model->insert ( $dataArr );
			if ($re > 0) {
				$this->_init ( $re );
			}
		}
		return $re;
	}
	/**
	 * 新用户数据初始化
	 */
	private function _init($uid) {}
	/**
	 * 修改密码
	 *
	 * @param string $email        	
	 * @param string $passwore        	
	 */
	public function rePwd($email, $passwore) {
		$dataArr = array(
				'password' => $passwore 
		);
		$whereArr = array(
				'email' => $email 
		);
		$re = $this->CI->user_model->update ( $dataArr, $whereArr );
		return $re;
	}
	/**
	 * 修改昵称
	 *
	 * @param string $email        	
	 * @param string $username        	
	 */
	public function reUsername($email, $username = '') {
		if ($username == '') {
			$this->CI->load->helper ( 'string' );
			$temp = explode ( '@', $email );
			$username = $temp[0] . random_string ( 'alnum', 5 );
		}
		$dataArr = array(
				'username' => $username 
		);
		$whereArr = array(
				'email' => $email 
		);
		$re = $this->CI->user_model->update ( $dataArr, $whereArr );
		return $re;
	}
	/**
	 * 验证是否存在该用户
	 *
	 * @param array $whereArr        	
	 */
	public function isExistUser($whereArr) {
		$re = $this->CI->user_model->count ( $whereArr );
		if ($re > 0) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 密码加密
	 */
	private function _encrypt($str) {
		$this->CI->load->library ( 'encrypt' );
		$re = $this->CI->encrypt->encode ( $str );
		return $re;
	}
	/**
	 * 密码解密
	 */
	private function _decrypt($str) {
		$this->CI->load->library ( 'encrypt' );
		$re = $this->CI->encrypt->decode ( $str );
		return $re;
	}

}